package wx

import (
	"strconv"
	//	"crypto/sha1"
	//	"io"
	"log"
	//	"sort"
	//	"strings"
	//	"fmt"
	models "mywechat/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/chanxuehong/wechat.v2/mp/core"
	"github.com/chanxuehong/wechat.v2/mp/menu"
	"github.com/chanxuehong/wechat.v2/mp/message/callback/request"
	"github.com/chanxuehong/wechat.v2/mp/message/callback/response"
)

var (
	msgHandler core.Handler
	msgServer  *core.Server
)

type WXCallackController struct {
	BaseController
}

func textMsgHandler(ctx *core.Context) {
	log.Printf("收到文本消息:\n%s\n", ctx.MsgPlaintext)
	beego.Informational(ctx.MsgPlaintext)
	event := request.GetText(ctx.MixedMsg)
	//	resp := response.NewText(msg.FromUserName, msg.ToUserName, msg.CreateTime, msg.Content)
	//	article := response.Article{"测试下", "很不错哟", "http://www.kuaifazs.com/img/banner03.png", "http://www.kuaifazs.com/"}
	//	articles := []response.Article{article}
	//	resp := response.NewNews(msg.FromUserName, msg.ToUserName, msg.CreateTime, articles)
	//	ctx.RawResponse(resp) // 明文回复
	//	ctx.AESResponse(resp, 0, "", nil) // aes密文回复

	if event.Content == "" {
		beego.Error("msg content is null")
		return
	}
	cidS := ctx.QueryParams.Get("cid")
	cid, err := strconv.ParseInt(cidS, 10, 64)
	if err != nil {
		beego.Error("textMsgHandler get cid error ", err.Error())
		return
	}
	content, msgType := models.GetTextReply(event.Content, cid)

	if len(content) == 0 {
		resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "无法处理您的请求，请入帮助")
		ctx.RawResponse(resp)
	} else if msgType == "text" {
		resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, content)
		ctx.RawResponse(resp)
	} else if msgType == "news" {
		articles, _ := models.GetArticleByNewsIds(content, cid)
		if len(*articles) == 0 {
			resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "无法处理您的请求，请入帮助")
			ctx.RawResponse(resp)
		} else {
			resp := response.NewNews(event.FromUserName, event.ToUserName, event.CreateTime, *articles)
			ctx.RawResponse(resp)
		}
	}
}

func defaultMsgHandler(ctx *core.Context) {
	log.Printf("收到消息:\n%s\n", ctx.MsgPlaintext)
	ctx.NoneResponse()
}

func menuClickEventHandler(ctx *core.Context) {
	log.Printf("收到菜单 click 事件:\n%s\n", ctx.MsgPlaintext)
	cidS := ctx.QueryParams.Get("cid")
	cid, err := strconv.ParseInt(cidS, 10, 64)
	if err != nil {
		beego.Error("textMsgHandler get cid error ", err.Error())
		return
	}
	event := menu.GetClickEvent(ctx.MixedMsg)
	//	resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "收到 click 类型的事件")
	if event.EventKey == "" {
		beego.Error("event ke is null")
		return
	}
	articles, err := models.GetArticleByEventKey(event.EventKey, cid)
	if err != nil {
		beego.Error("GetArticleByEventKey error is :%s", err.Error())
		return
	}
	if len(*articles) == 0 {
		resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "敬请等待开放……")
		ctx.RawResponse(resp)
	} else {
		resp := response.NewNews(event.FromUserName, event.ToUserName, event.CreateTime, *articles)
		ctx.RawResponse(resp)
	}

}
func subscribeEventHandler(ctx *core.Context) {
	event := request.GetSubscribeEvent(ctx.MixedMsg)
	resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "敬请等待开放……")

	ctx.RawResponse(resp) // 明文回复
}

func defaultEventHandler(ctx *core.Context) {
	log.Printf("收到事件:\n%s\n", ctx.MsgPlaintext)
	ctx.NoneResponse()
}

var msgServerMap = make(map[int64]*core.Server)

func init() {
	beego.SetLogger("file", `{"filename":"logs/callback.log","level":3,"maxdays":1}`)
	beego.SetLogFuncCall(true)
	mux := core.NewServeMux()
	mux.DefaultMsgHandleFunc(defaultMsgHandler)
	mux.DefaultEventHandleFunc(defaultEventHandler)
	mux.MsgHandleFunc(request.MsgTypeText, textMsgHandler)
	mux.EventHandleFunc(menu.EventTypeClick, menuClickEventHandler)
	mux.EventHandleFunc(request.EventTypeSubscribe, subscribeEventHandler)

	msgHandler = mux
	var maps []orm.Params
	o := orm.NewOrm()
	_, err := o.QueryTable("company_info").Filter("IsDelete__exact", 0).Values(&maps, "Id", "WxAppId", "WxAppSecret", "WxToken", "WxOriId", "WxEncodedAesKey")
	if err != nil {
		beego.Error("get company info error is :%s", err.Error())
	}
	for _, m := range maps {
		msgServerMap[m["Id"].(int64)] = core.NewServer(m["WxOriId"].(string), m["WxAppId"].(string), m["WxToken"].(string), m["WxEncodedAesKey"].(string), msgHandler, nil)
		wechatClientMap[m["Id"].(int64)] = core.NewClient(core.NewDefaultAccessTokenServer(m["WxAppId"].(string), m["WxAppSecret"].(string), nil), nil)
	}
	//	msgServer = core.NewServer(beego.AppConfig.String("wxOriId"), beego.AppConfig.String("wxAppId"), beego.AppConfig.String("wxToken"), beego.AppConfig.String("wxEncodedAESKey"), msgHandler, nil)
}

func (this *WXCallackController) Get() {
	cid, err := this.GetInt64("cid")
	if err != nil {
		beego.Error("post request company id error is :%s", err.Error())
		this.StopRun()
	}
	msgServerMap[cid].ServeHTTP(this.Ctx.ResponseWriter, this.Ctx.Request, nil)
	this.StopRun()

}

func (this *WXCallackController) Post() {
	cid, err := this.GetInt64("cid")
	if err != nil {
		beego.Error("post request company id error is :%s", err.Error())
		this.StopRun()
	}
	msgServerMap[cid].ServeHTTP(this.Ctx.ResponseWriter, this.Ctx.Request, nil)
	this.StopRun()

}
